package com.example.remotecontrol.ui.remote

import android.os.VibrationEffect
import android.os.Vibrator
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.remotecontrol.data.model.Device
import com.example.remotecontrol.data.model.DeviceControlType
import com.example.remotecontrol.data.model.TVRemoteCode
import com.example.remotecontrol.data.repository.DeviceRepository
import com.example.remotecontrol.data.repository.SettingsRepository
import com.example.remotecontrol.util.IRManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 遥控器界面的ViewModel
 */
@HiltViewModel
class RemoteViewModel @Inject constructor(
    private val deviceRepository: DeviceRepository,
    private val settingsRepository: SettingsRepository,
    private val irManager: IRManager,
    private val vibrator: Vibrator
) : ViewModel() {

    // 当前选中的设备
    private val _selectedDevice = MutableStateFlow<Device?>(null)
    val selectedDevice: StateFlow<Device?> = _selectedDevice.asStateFlow()
    
    // 最近使用的设备列表
    val recentDevices = deviceRepository.recentDevices
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )
    
    // 红外发射器是否可用
    private val _irAvailable = MutableStateFlow(false)
    val irAvailable: StateFlow<Boolean> = _irAvailable.asStateFlow()
    
    // 命令执行状态
    private val _commandStatus = MutableStateFlow<CommandStatus>(CommandStatus.Idle)
    val commandStatus: StateFlow<CommandStatus> = _commandStatus.asStateFlow()
    
    init {
        // 检查设备是否支持红外功能
        _irAvailable.value = irManager.hasIrEmitter()
        
        // 自动选择最近使用的设备
        viewModelScope.launch {
            val devices = recentDevices.first()
            if (devices.isNotEmpty()) {
                _selectedDevice.value = devices.first()
            }
        }
    }
    
    /**
     * 选择设备
     */
    fun selectDevice(device: Device) {
        _selectedDevice.value = device
    }
    
    /**
     * 发送红外命令
     */
    fun sendIRCommand(command: String) {
        viewModelScope.launch {
            val device = _selectedDevice.value ?: return@launch
            
            // 如果设备不支持红外控制，则返回
            if (device.controlType != DeviceControlType.IR || !irAvailable.value) {
                _commandStatus.value = CommandStatus.Error("设备不支持红外控制")
                return@launch
            }
            
            // 获取红外数据
            val irData = device.irData
            if (irData == null) {
                _commandStatus.value = CommandStatus.Error("设备红外数据不可用")
                return@launch
            }
            
            // 获取命令码
            val commandCode = irData.commandMap[command]
            if (commandCode == null) {
                _commandStatus.value = CommandStatus.Error("命令未找到: $command")
                return@launch
            }
            
            // 设置命令状态为执行中
            _commandStatus.value = CommandStatus.Sending
            
            // 触发震动反馈
            if (settingsRepository.vibrationEnabled.first()) {
                vibrator.vibrate(VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE))
            }
            
            // 发送红外命令
            val success = irManager.transmitNEC(irData.addressCode, commandCode)
            
            // 更新命令状态
            _commandStatus.value = if (success) {
                CommandStatus.Success
            } else {
                CommandStatus.Error("发送命令失败")
            }
            
            // 更新设备使用时间
            deviceRepository.updateDeviceLastUsed(device.id)
        }
    }
    
    /**
     * 发送通用TV命令
     * 如果没有选择设备，使用默认的三星电视码
     */
    fun sendGenericTVCommand(command: String) {
        viewModelScope.launch {
            // 如果没有选择设备或设备不支持红外，使用通用命令
            if (_selectedDevice.value == null || _selectedDevice.value?.controlType != DeviceControlType.IR) {
                // 使用默认的三星电视码
                val brandCode = TVRemoteCode.getAddressCode("samsung")
                val commandMap = TVRemoteCode.getCommandMap("samsung")
                val commandCode = commandMap[command]
                
                if (commandCode != null && irAvailable.value) {
                    // 设置命令状态为执行中
                    _commandStatus.value = CommandStatus.Sending
                    
                    // 触发震动反馈
                    if (settingsRepository.vibrationEnabled.first()) {
                        vibrator.vibrate(VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE))
                    }
                    
                    // 发送红外命令
                    val success = irManager.transmitNEC(brandCode, commandCode)
                    
                    // 更新命令状态
                    _commandStatus.value = if (success) {
                        CommandStatus.Success
                    } else {
                        CommandStatus.Error("发送命令失败")
                    }
                } else {
                    _commandStatus.value = CommandStatus.Error("命令未找到: $command")
                }
            } else {
                // 使用选定的设备发送命令
                sendIRCommand(command)
            }
        }
    }
    
    /**
     * 清除命令状态
     */
    fun clearCommandStatus() {
        _commandStatus.value = CommandStatus.Idle
    }
}

/**
 * 命令执行状态
 */
sealed class CommandStatus {
    object Idle : CommandStatus()
    object Sending : CommandStatus()
    object Success : CommandStatus()
    data class Error(val message: String) : CommandStatus()
} 